#include<stdio.h>
#include<pthread.h>
int ticket[10]= {1,3,5,7,9,2,4,6,8,10};
int rest=10;
int th_num[2]= {1,2};
pthread_mutex_t p_mutex;
void *terminal(void *p)
{
    int mynum=*((int *)p);
    int tot=0;
    long i;
    while(1)
    {
        pthread_mutex_lock(&p_mutex);
        if(rest>0)
        {
            rest--;
            tot++;
            for(i=0; i<9999999; i++);
            printf("Terminal_%d:sell a ticket,num=%d.\n",mynum,ticket[rest]);
        }
        else
        {
            pthread_mutex_unlock(&p_mutex);
            break;
        }
        pthread_mutex_unlock(&p_mutex);
        for(i=0; i<9999999; i++);
    }
    printf("Terminal_%d selled %d tickets.\n",mynum,tot);
    pthread_exit(0);
}
int main()
{
    pthread_t tid[2];
    pthread_mutex_init(&p_mutex,NULL);
    pthread_create(&tid[0], NULL, terminal, &th_num[0]);
    pthread_create(&tid[1], NULL, terminal, &th_num[1]);
    pthread_join(tid[0],NULL);
    pthread_join(tid[1],NULL);
    pthread_mutex_destroy(&p_mutex);
    printf("Over!\n");
    return 0;
}
